package com.yeyixiao.blog.controller;

import com.yeyixiao.blog.common.page.Pagination;
import com.yeyixiao.blog.domain.Article;
import com.yeyixiao.blog.domain.Comment;
import com.yeyixiao.blog.service.ArticleService;
import com.yeyixiao.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class IndexControler {
    @Autowired
    ArticleService arts;
    @Autowired
    CommentService coms;
    private String pass = PassWord.password;

    @GetMapping()
    public ModelAndView index(String c, String sort, Pagination<Article> page) {
        System.out.println("进入controllerindex");
        //System.out.println("test");
        ModelAndView mv = new ModelAndView("index");
        Article queryEntity = new Article();
        for (Article art : arts.queryAll(queryEntity)) {
            System.out.println(art.getName());
        }

        //mv.addObject("item", list);
        page.setPageSize(10);
        if("last".equals(sort)){
            page.setSortField("id");
        }
        if("pop".equals(sort)){
            page.setSortField("study_count");//字段的值
        }
        mv.addObject("sort",sort);
        page = arts.queryPage(queryEntity,page);
        List<Article> list = page.getItems();
        for (Article entity : list) {
            if (entity.getContent().length() > 40) {
                entity.setDes(entity.getContent().substring(0, 40) + "...");
            } else {
                entity.setDes(entity.getContent());
            }
        }
        page.setItems(list);

        mv.addObject("page",page);
        //mv.addObject("base","localhost:8080");
        return mv;
    }

    @RequestMapping("add")
    public ModelAndView add() {
        System.out.println("进入controller5");
        return new ModelAndView("add");
    }

    @RequestMapping({"/article/toIndex", "toIndex"})
    public ModelAndView toIndex() {
        System.out.println("进入controller toIndex");
        return new ModelAndView("toIndex");
    }

    private boolean check(String password) {
        return password.equalsIgnoreCase(pass) ? true : false;
    }

    @PostMapping("submit")
    @ResponseBody
    public String submit(String title, String content, String password, HttpServletRequest request) {
        System.out.println("进入controller4");
        if (check(password)) {
            Article art = new Article();
            art.setContent(content);
            art.setName(title);
            art.setPlay(0);
            art.setLike(0);
            /////return title;
            arts.createCourse(art);

            return "<script>alert(\"提交完成！\");window.location.href=\"../\";</script>";
        } else {
            return "<script>alert(\"密码错误！\");window.location.href=\"../\";</script>";
        }
    }
    @PostMapping("doedit")
    @ResponseBody
    public String doedit(String title, String content, String password, String id,HttpServletRequest request) {
            System.out.println("进入controller edit");
            Long sid;
            try {
                sid = Long.parseLong(id);
            } catch (Exception e) {
                System.out.println("error!");
                return "ID转换中发生错误！error!";
            }
        if (check(password)) {
            if(sid!=null || title.equals("") || content.equals("")) {
                Article art = arts.getById(sid);
                art.setContent(content);
                art.setName(title);
                art.setDate(new Date());
                /////return title;
                arts.update(art);
            }
            else{
                return "<script>alert(\"填写信息错误！\");window.location.href=\"../\";</script>";
            }
            return "<script>alert(\"提交完成！\");window.location.href=\"../\";</script>";
        } else {
            return "<script>alert(\"密码错误！\");window.location.href=\"../\";</script>";
        }
    }

    @RequestMapping("404")
    public ModelAndView error() {
        System.out.println("进入controller3");
        return new ModelAndView("404");
    }

    @RequestMapping("/article/{articleId}")
    public ModelAndView article(@PathVariable Long articleId) {
        System.out.println("进入controller2");
        if (articleId == null) {
            return new ModelAndView("404");
        }
        Article art = arts.getById(articleId);
        if (art == null) {
            return new ModelAndView("404");
        }
        art.addPlay();
        arts.update(art);
        ModelAndView mv = new ModelAndView("show");
        mv.addObject("art", art);
        mv.addObject("date", new SimpleDateFormat("yyyy-MM-dd").format(art.getDate()));
        mv.addObject("comment", coms.queryByArticle(articleId));
        for(Comment comment : (coms.queryByArticle(articleId))){
            System.out.println(comment.getDate());
        }
        return mv;
    }

    @PostMapping("/like")
    @ResponseBody
    public String like(String id, HttpServletRequest request) {
        Long sid;
        try {
            sid = Long.parseLong(id);
        } catch (Exception e) {
            System.out.println("error!");
            return "error!";
        }
        System.out.println("进入controller");
        if (null == sid || 0 == sid) {
            return "error!";
        }
        Article art = arts.getById(sid);
        if (art == null) {
            return "error!";
        }
        if (art.getLike() == 0) {
            art.setLike(1);
        } else {
            art.setLike(art.getLike() + 1);
        }
        arts.update(art);
        return "<script>window.location.replace(document.referrer);</script>";
    }

    @PostMapping("delete")
    @ResponseBody
    public String delete(String password, Long id, HttpServletRequest request) {
        if (check(password)) {
            /*Long sid;
            try {
                sid = Long.parseLong(id);
            } catch (Exception e) {
                System.out.println("error!");
                return "转换中发送错误！error!";
            }*/
            System.out.println("进入controller delete，ID为" + id);
            if (null == id || 0 == id) {
                return "ID为空或0！error!";
            }
            Article art = arts.getById(id);
            if (art == null) {
                return "error!";
            }
            arts.delete(art);
            List<Comment> comments=coms.queryByArticle(id);
            for(Comment comment : comments){
                coms.delete(comment);
            }
            return "<script>alert('删除成功！');window.location.replace('toIndex');</script>";
        } else {
            return "<script>alert('密码错误！');window.location.replace(document.referrer);</script>";
        }
    }

    @PostMapping("newcomments")
    @ResponseBody
    public String newcomments(String user, String content, String id, HttpServletRequest request) {
        if(!user.equals("") ||!content.equals("")) {
            Long sid;
            try {
                sid = Long.parseLong(id);
            } catch (Exception e) {
                System.out.println("error!");
                return "转换中发生错误！error!";
            }
            //sid=id;
            System.out.println("进入controller delete，ID为" + sid);
            if (null == id || 0 == sid) {
                return "ID为空或0！error!";
            }
            Article art = arts.getById(sid);
            if (art == null) {
                return "error!";
            }

            Comment comment = new Comment();
            comment.setContent(content);
            comment.setUser(user);
            comment.setArticleID(sid);
            comment.setIp("本地地址："+request.getLocalAddr()+"远端主机名:"+request.getRemoteHost()+"远端地址:"+request.getRemoteAddr()+"远端用户:"+request.getRemoteUser());
            coms.createComment(comment);
            return "<script>window.location.replace(document.referrer);</script>";
        }
        else{return "<script>alert('用户名或正文为空！');window.location.replace(document.referrer);</script>";}
    }
    @GetMapping("edit")
    public ModelAndView edit(Long id){
        ModelAndView mv=new ModelAndView("edit");
        if(id==null) return new ModelAndView("404");
        Article art=arts.getById(id);
        if(art==null){return new ModelAndView("404");}
        mv.addObject("art",art);
        return mv;
    }

}
